package org.dromara.pill.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.pill.domain.PillFactory;
import org.dromara.pill.mapper.PillFactoryMapper;
import org.springframework.stereotype.Service;
import org.dromara.pill.domain.bo.PillDrugBo;
import org.dromara.pill.domain.vo.PillDrugVo;
import org.dromara.pill.domain.PillDrug;
import org.dromara.pill.mapper.PillDrugMapper;
import org.dromara.pill.service.IPillDrugService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 药品信息Service业务层处理
 *
 * @author Lion Li
 * @date 2023-07-07
 */
@RequiredArgsConstructor
@Service
public class PillDrugServiceImpl implements IPillDrugService {

    private final PillDrugMapper baseMapper;
    private final PillFactoryMapper pillFactoryMapper;

    /**
     * 查询药品信息
     */
    @Override
    public PillDrugVo queryById(Long drugId){
        return baseMapper.selectVoById(drugId);
    }

    /**
     * 查询药品信息列表
     */
    @Override
    public TableDataInfo<PillDrugVo> queryPageList(PillDrugBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PillDrug> lqw = buildQueryWrapper(bo);
        Page<PillDrugVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);

    }

    /**
     * 分页条件查询 药品信息
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<PillDrugVo> selectPagePillDrugVoList(PillDrugBo bo, PageQuery pageQuery) {
        Page<PillDrugVo>  page = baseMapper.selectPagePillDrugVoList(pageQuery.build(), this.buildQueryWrapperPillDrugVo(bo));
        return TableDataInfo.build(page);
    }

    private Wrapper<PillDrug> buildQueryWrapperPillDrugVo(PillDrugBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<PillDrug> wrapper = Wrappers.query();
//        wrapper.eq("u.del_flag", UserConstants.USER_NORMAL)
        wrapper
            .eq(ObjectUtil.isNotNull(bo.getDrugId()), "d.drug_id", bo.getDrugId())
            .eq(ObjectUtil.isNotNull(bo.getDrugType()), "d.drug_type", bo.getDrugType())
            .like(StringUtils.isNotBlank(bo.getDrugName()), "d.drug_name", bo.getDrugName())
//            .eq(StringUtils.isNotBlank(bo.getStatus()), "d.status", bo.getStatus())
            .between(params.get("beginTime") != null && params.get("endTime") != null,
                "d.create_time", params.get("beginTime"), params.get("endTime"))
            .and(ObjectUtil.isNotNull(bo.getDrugId()), w -> {
                List<PillFactory> factoryList = pillFactoryMapper.selectList(new LambdaQueryWrapper<PillFactory>()
                    .select(PillFactory::getFactoryId)
                    .apply(DataBaseHelper.findInSet(bo.getDrugId(), "ancestors")));
                List<Long> ids = StreamUtils.toList(factoryList, PillFactory::getFactoryId);
                ids.add(bo.getFactoryId());
                w.in("d.factory_id", ids);
            });
        return wrapper;
    }
    /**
     * 查询药品信息列表
     */
    @Override
    public List<PillDrugVo> queryList(PillDrugBo bo) {
        LambdaQueryWrapper<PillDrug> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PillDrug> buildQueryWrapper(PillDrugBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PillDrug> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getDrugName()), PillDrug::getDrugName, bo.getDrugName());
        lqw.like(bo.getFactoryId() != null, PillDrug::getFactoryId, bo.getFactoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getDrugType()), PillDrug::getDrugType, bo.getDrugType());
        lqw.eq(StringUtils.isNotBlank(bo.getPrescriptionType()), PillDrug::getPrescriptionType, bo.getPrescriptionType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PillDrug::getStatus, bo.getStatus());
        return lqw;
    }
    /**
     * 新增药品信息
     */
    @Override
    public Boolean insertByBo(PillDrugBo bo) {
        PillDrug add = MapstructUtils.convert(bo, PillDrug.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setDrugId(add.getDrugId());
        }
        return flag;
    }

    /**
     * 修改药品信息
     */
    @Override
    public Boolean updateByBo(PillDrugBo bo) {
        PillDrug update = MapstructUtils.convert(bo, PillDrug.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PillDrug entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除药品信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
